<template>
  <BasicDrawer
    v-bind="$attrs"
    title="菜单预览"
    :width="drawerWidth"
    @register="registerDrawerInner"
    @close="handleClose"
  >
    <Menu
      v-if="currentMenuTree.length"
      class="w-230px"
      mode="inline"
      :selectable="false"
      :items="currentMenuTree"
      :theme
      v-model:openKeys="openKeys"
    />
    <Empty v-else />
  </BasicDrawer>
</template>

<script setup lang="ts">
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { useMaxWidthOrDefault } from '@/hooks/web/useSize';
  import { Menu, Empty } from 'ant-design-vue';
  /** 只有超级管理员可以操作租户 不用单选这里的权限问题 */
  import { menuList } from '@/api/system/menu';
  import type { Menu as MenuType } from '@/api/system/menu/model';
  import { computed, onMounted, ref } from 'vue';
  import { listToTree, removeEmptyChildren, findIdsByLevel } from '@/utils/helper/treeHelper';
  import { useRender } from '@/hooks/component/useRender';
  import { useAppStore } from '@/store/modules/app';
  import { ThemeEnum } from '@/enums/appEnum';

  const drawerWidth = useMaxWidthOrDefault(600);
  const [registerDrawerInner] = useDrawerInner(openCallback);

  const appStore = useAppStore();
  /** 为啥要套一层 因为插件报错-- */
  const theme = computed<ThemeEnum>(() => {
    return appStore.getDarkMode as ThemeEnum;
  });

  /** 全部的菜单 */
  const allMenuList = ref<MenuType[]>([]);
  /** 用正确的类型为啥还报错??? */
  const currentMenuTree = ref<any[]>([]);
  /** 展开的菜单项 */
  const openKeys = ref<string[]>([]);
  /** 默认展开两层菜单 */
  const defaultExpandLevel = 2;

  /**
   * 获取全部菜单信息 只会在mounted获取一次
   */
  onMounted(async () => {
    const ret = await menuList();
    /** 去除'按钮' */
    allMenuList.value = ret.filter((item) => item.menuType !== 'F');
  });

  const { renderIcon } = useRender();
  function transformToAntMenu(menuList: MenuType[]) {
    const list = menuList.map((item) => ({
      key: String(item.menuId),
      parentKey: String(item.parentId),
      icon: renderIcon(item.icon),
      label: item.menuName,
      title: item.menuName,
    }));
    /** 转为树形结构 */
    const menuTree = listToTree(list, { id: 'key', pid: 'parentKey' });
    /** 去掉空的children */
    removeEmptyChildren(menuTree);
    return menuTree;
  }

  function openCallback(menuIdStr: string) {
    /** 拿到join后的数组 如1, 2, 3 */
    const menuIds = menuIdStr.split(', ');

    /** 找到对应的菜单 */
    const currentMenuList = allMenuList.value.filter((item) => {
      return menuIds.includes(String(item.menuId));
    });

    /** 设置为当前 */
    currentMenuTree.value = transformToAntMenu(currentMenuList);

    /** 默认展开两层菜单 */
    const foundByLevel = findIdsByLevel(defaultExpandLevel, currentMenuTree.value, {
      id: 'key',
      pid: 'parentKey',
    }) as string[];
    /** 设置展开的菜单 */
    openKeys.value = foundByLevel;
  }

  function handleClose() {
    openKeys.value = [];
    currentMenuTree.value = [];
  }
</script>

<style scoped></style>
